package com.pjedu.nbmallwebsitesystem.web;

import com.pjedu.nbmallcommon.common.Constants;
import com.pjedu.nbmallcommon.common.MallException;
import com.pjedu.nbmallcommon.common.ServiceResultEnum;
import com.pjedu.nbmallcommon.utils.Result;
import com.pjedu.nbmallcommon.utils.ResultGenerator;
import com.pjedu.nbmallshop.service.MallOrderService;
import com.pjedu.nbmallshop.service.MallShoppingCartService;
import com.pjedu.nbmallshop.service.PayService;
import com.pjedu.nbmallshop.vo.MallOrderDetailVO;
import com.pjedu.nbmallshop.vo.MallShoppingCartItemVO;
import com.pjedu.nbmalluser.entity.MallUser;
import com.pjedu.nbmalluser.service.MallUserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
public class OrderController {

    @Resource
    private MallShoppingCartService mallShoppingCartService;
    @Resource
    private MallOrderService mallOrderService;
    @Resource
    private PayService payService;
    @Resource
    private MallUserService mallUserService;

    @GetMapping("/orderDetail")
    public String orderDetailPage(HttpServletRequest request, String orderNo, @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        MallOrderDetailVO orderDetailVO = mallOrderService.getOrderDetailByOrderNo(orderNo, loginUserId);
        if (orderDetailVO == null) {
            return "error/error_5xx";
        }
        request.setAttribute("orderDetailVO", orderDetailVO);
        return "mall/order-detail";
    }

    @GetMapping("/order/all")
    public String orderListPage(@RequestParam Map<String, Object> params, HttpServletRequest request,
                                @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        params.put("userId", loginUserId);
        if (StringUtils.isEmpty(params.get("page"))) {
            params.put("page", 1);
        }
        params.put("limit", Constants.ORDER_SEARCH_PAGE_LIMIT);
        //封装我的订单数据
        HashMap pageUtil = new HashMap(params);
        request.setAttribute("orderPageResult", mallOrderService.getMyOrders(pageUtil));
        request.setAttribute("path", "orders");
        return "mall/personal/my-orders";
    }

    @RequestMapping("/saveOrder")
    @ResponseBody
    public Result saveOrder(Integer payType, @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        MallUser user = mallUserService.getUserDetailById(loginUserId);
        List<MallShoppingCartItemVO> myShoppingCartItems = mallShoppingCartService.getMyShoppingCartItems(user.getUserId());
        if (StringUtils.isEmpty(user.getAddress().trim())) {
            //无收货地址
            MallException.fail(ServiceResultEnum.NULL_ADDRESS_ERROR.getResult());
        }
        if (CollectionUtils.isEmpty(myShoppingCartItems)) {
            //购物车中无数据则跳转至错误页
            MallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
        }
        // 保存订单并返回订单号【待支付状态】
        String saveOrderResult = mallOrderService.saveOrder(user, myShoppingCartItems, payType);
        return ResultGenerator.genSuccessResult(saveOrderResult);
    }

    @PutMapping("/orders/{orderNo}/cancel")
    @ResponseBody
    public Result cancelOrder(@PathVariable("orderNo") String orderNo, @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        String cancelOrderResult = mallOrderService.cancelOrder(orderNo, loginUserId);
        if (ServiceResultEnum.SUCCESS.getResult().equals(cancelOrderResult)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(cancelOrderResult);
        }
    }

    @PutMapping("/orders/{orderNo}/finish")
    @ResponseBody
    public Result finishOrder(@PathVariable("orderNo") String orderNo, @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        String finishOrderResult = mallOrderService.finishOrder(orderNo, loginUserId);
        if (ServiceResultEnum.SUCCESS.getResult().equals(finishOrderResult)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(finishOrderResult);
        }
    }
    
    
    // 发起支付请求
    @GetMapping(value = "/pay")
    public void payOrder(String orderNo, HttpServletResponse response) throws IOException {
        // TODO 此代码集成了支付宝， 微信等其他方式类似
        String form = payService.aliapyForm(orderNo);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(form);//直接将完整的表单html输出到页面
        out.flush();
        out.close();
    }

    // 支付完毕 跳转的连接
    @GetMapping("/paySuccess")
    public String paySuccess(HttpServletRequest request) throws Exception {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        mallOrderService.paySuccess(params);
        // 跳转个人订单中心即可
        return "redirect:/order/all";
    }

}
